<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page import="za.org.foobar.famon.model.*" %>
<%@ page import="za.org.foobar.famon.simpleui.PageUtil" %>
<%@ page import="za.org.foobar.famon.simpleui.SimpleUiUtil" %>
<%@ page import="za.org.foobar.famon.util.DBQuery" %>
<%@ page import="java.util.List" %>
<%@ page import="za.org.foobar.famon.webapp.FailureLogic" %>
<%@ page import="za.org.foobar.famon.webapp.ApplicationLogic" %>
<%@ page import="za.org.foobar.famon.webapp.FamonSecurityException" %>
<%@ page import="za.org.foobar.famon.util.ServerUtil" %>
<%@ page import="za.org.foobar.famon.util.DB" %>
<%

    Log log = LogFactory.getLog("za.org.foobar.famon.web.index.jsp");
    
    ApplicationLogic applicationLogic = ApplicationLogic.get();
    FailureLogic failureLogic = FailureLogic.get();
    String paramApplicationGroupId = ServerUtil.urlDecode(request.getParameter("applicationGroupId"));
    String paramAddUserEmail = ServerUtil.urlDecode(request.getParameter("addUserEmail"));//POST
    String paramEditUserId = ServerUtil.urlDecode(request.getParameter("editUserId"));
    String paramDelUserId = ServerUtil.urlDecode(request.getParameter("delUserId"));
    String paramUserRole = ServerUtil.urlDecode(request.getParameter("userRole"));//POST
    String paramEditApplicationName = ServerUtil.urlDecode(request.getParameter("editApplicationName"));//POST
    String paramEditIsPrivate = ServerUtil.urlDecode(request.getParameter("editIsPrivate"));//POST
    String paramEditInstanceName = ServerUtil.urlDecode(request.getParameter("editInstanceName"));//POST
    String paramEditVersionName = ServerUtil.urlDecode(request.getParameter("editVersionName"));//POST

    String baseUrl = SimpleUiUtil.getCurrentUrl(request).replaceAll(
            "[&]((editUserId)|(delUserId))[\\=][^&]+", ""
    );

    PageUtil pageUtil = new PageUtil(request);
    PageUtil userPageUtil = new PageUtil(request, "user");

    StringBuilder error = new StringBuilder();
    boolean doneEdit = false;

    ApplicationGroup applicationGroup = null;
    if (paramApplicationGroupId != null && paramApplicationGroupId.length() > 0) {
        try {
            applicationGroup = applicationLogic.getApplicationGroup(
                    ApplicationGroup.stringToKey(paramApplicationGroupId));
        } catch (NumberFormatException ignored) {
            log.error("Invalid id: \"" + paramApplicationGroupId + "\"");
        } catch (FamonSecurityException e) {
            if (SimpleUiUtil.handleSecurityException(request, response, error)) {
                return;
            }
        }
    }
    if (applicationGroup != null && paramAddUserEmail != null) {
        if (paramAddUserEmail.length() == 0) {
            SimpleUiUtil.addError(error, "Unable to add user: you must specify the user's email address");
        } else {
            applicationLogic.addApplicationUser(applicationGroup.getApplication(), paramAddUserEmail);
            doneEdit = true;            
        }
    }
    if (applicationGroup != null && paramEditApplicationName != null && paramEditApplicationName.length() > 0) {
        Application app = applicationGroup.getApplication();
        app.setName(paramEditApplicationName);
        app.setPrivate(paramEditIsPrivate != null);
        doneEdit = true;
    }
    if (applicationGroup != null && paramEditInstanceName != null && paramEditInstanceName.length() > 0) {
        applicationGroup.getApplicationInstance().setName(paramEditInstanceName);
        doneEdit = true;
    }
    if (applicationGroup != null && paramEditVersionName != null && paramEditVersionName.length() > 0) {
        applicationGroup.getApplicationVersion().setName(paramEditVersionName);
        doneEdit = true;
    }

%>
<html>
<head>
    <title>Failures</title>
    <link rel="stylesheet" href="simpleui.css"/>
    <link rel="stylesheet" href="bluedream.css"/>
</head>
<body>
<%=SimpleUiUtil.renderLoginHeader(request)%>
<div class="breadCrumb">
    <a href="index.jsp">Failures</a>
    <%
    if (applicationGroup != null) {
        %> &gt; <a href="index.jsp?applicationGroupId=<%=applicationGroup.keyToString()%>"><%=
            applicationGroup.getTitle()%></a><%
    }
    %>
</div>
<div class="body">
<%
    if (error.length() > 0) {
        out.print(error.toString());
    } else if (applicationGroup == null) {
        %><table width="100%">
            <caption>Application Groups</caption>
            <thead>
                <tr>
                    <th>Application</th>
                    <th>Instance</th>
                    <th>Version</th>
                </tr>
            </thead>
            <tbody>
            <%
                List<ApplicationGroup> applicationGroupList = applicationLogic.getApplicationGroupList(null, null, null);
                applicationGroupList = pageUtil.getResultList(applicationGroupList);
                pageUtil.printPagesTr(out, 3);
                boolean odd = true;
                for (ApplicationGroup g : applicationGroupList) {
                    %><tr<%=odd ? " class=\"odd\"" : "" %>>
                        <td><a href="index.jsp?applicationGroupId=<%=g.keyToString()%>"><%=g.getApplication().getName()%></a></td>
                        <td><a href="index.jsp?applicationGroupId=<%=g.keyToString()%>"><%=g.getApplicationInstance().getName()%></a></td>
                        <td><a href="index.jsp?applicationGroupId=<%=g.keyToString()%>"><%=g.getApplicationVersion().getName()%></a></td>
                    </tr><%
                    odd = !odd;
                }
                pageUtil.printPagesTr(out, 3);
            %>
            </tbody>
        </table><%
    } else {
        Application app = applicationGroup.getApplication();
        ApplicationUser editAppUser = null;
        if (paramEditUserId != null) {
            editAppUser = applicationLogic.getApplicationUser(ApplicationUser.stringToKey(app.getId(), paramEditUserId));
            if (paramUserRole != null) {
                editAppUser.setRole(Integer.parseInt(paramUserRole));
                editAppUser = null;
            }
        }
        if (paramDelUserId != null) {
            applicationLogic.deleteApplicationUser(ApplicationUser.stringToKey(app.getId(), paramEditUserId));
        }

        %><table width="100%">
            <caption><%=applicationGroup.getTitle()%></caption>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Message</th>
                </tr>
            </thead>
            <tbody>
            <%
                DBQuery<Failure> failureQuery = failureLogic.getFailureQuery(applicationGroup.getId(), null);
                List<Failure> failureList = pageUtil.getResultList(failureQuery, false);
                pageUtil.printPagesTr(out, 3);
                boolean odd = true;
                for (Failure f : failureList) {
                    %><tr<%=odd ? " class=\"odd\"" : "" %>>
                        <td><%=f.getDate()%></td>
                        <td><a href="failure.jsp?failureId=<%=f.keyToString()%>"><%=f.getFailureType()%></a></td>
                        <td><%=f.getMessage()%></td>
                    </tr><%
                    odd = !odd;
                }
                pageUtil.printPagesTr(out, 3);
            %>
            </tbody>
        </table>
        <%
        if (applicationLogic.canEditApplication(app)) {
            %>
            <br>
            <a name="UserList"></a>
            <table width="100%">
                <caption>Users</caption>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Verified</th>
                        <th>Role</th>
                        <th>Alert Regex</th>
                        <th>Edit</th>
                    </tr>
                </thead>
                <tbody>
                <%
                    List<ApplicationUser> userList = app.getUserList();
                    userList = userPageUtil.getResultList(userList);
                    userPageUtil.printPagesTr(out, 6);
                    odd = true;
                    for (ApplicationUser appUser : userList) {
                        UserData u = appUser.getUser();
                        %><tr<%=odd ? " class=\"odd\"" : "" %>>
                            <td><%=SimpleUiUtil.toString(u.getNickname())%></td>
                            <td><%=SimpleUiUtil.toString(u.getEmail())%></td>
                            <td><%=SimpleUiUtil.toString(u.getUser() != null)%></td>
                            <td><%=RoleEnum.toString(appUser.getRole())%></td>
                            <td><%=SimpleUiUtil.toString(appUser.getAlertRegex())%></td>
                            <td><a href="<%=baseUrl%>&editUserId=<%=appUser.keyToString()%>">edit</a>
                                <a href="<%=baseUrl%>&delUserId=<%=appUser.keyToString()%>">delete</a>
                            </td>
                        </tr><%
                        odd = !odd;
                    }
                    userPageUtil.printPagesTr(out, 6);
                %>
                </tbody>
            </table>
            <br>
            <form action="<%=baseUrl%>" method="POST">
                <label>Application: <input type="text" name="editApplicationName" value="<%=app.getName()%>"/></label><br>
                <label>Is Private: <input type="checkbox" name="editIsPrivate"<%=app.isPrivate() ? " checked" : ""%>/></label><br>
                <label>Instance: <input type="text" name="editInstanceName" value="<%=applicationGroup.getApplicationInstance().getName()%>"/></label><br>
                <label>Version: <input type="text" name="editVersionName" value="<%=applicationGroup.getApplicationVersion().getName()%>"/></label><br>
                <input type="submit" value="Save"/>
            </form>
            <br>
            <form action="<%=baseUrl%>#UserList" method="POST">
                <%
                    if (editAppUser != null) {
                        %>
                        <input type="hidden" name="editUserId" value="<%=paramEditUserId%>"/>
                        <label>Editing <%=editAppUser.getUser().getEmail()%></label><br>
                        <label>Role:</label>
                        <label><input type="radio" name="userRole" value="<%=RoleEnum.user()%>"<%=editAppUser.getRole() == RoleEnum.user() ? " checked=\"yes\"" : "" %>> User</label>
                        <label><input type="radio" name="userRole" value="<%=RoleEnum.admin()%>"<%=editAppUser.getRole() == RoleEnum.admin() ? " checked=\"yes\"" : "" %>> Admin</label><br>
                        <%
                    } else {
                        %>
                        <label>Add user by Email:
                            <input type="text" name="addUserEmail"/>
                        </label><br>
                        <%
                    }
                    %>
                <input type="submit" value="Save"/>
            </form>
            <%
        }
    }
%>
</div>

</body>
</html>
<%
    if (doneEdit) {
        DB.closePM();
    }
%>